package services

import (
	"encoding/json"
	"fmt"

	"github.com/sirupsen/logrus"
)

// 解析DEVICE_CONTROL数据
func (d *DeviceData) ParseDeviceControlData() error {
	// 校验数据长度
	if len(d.RegisterData) < 13 {
		return fmt.Errorf("payload:%v data length is invalid", d.RegisterData)
	}
	// DEVICE_CONTROL是设备事件数据
	deviceControlParams := DeviceControlParams{
		SwitchSprinkling:       d.RegisterData[0],
		SolenoidValveDelay:     d.RegisterData[1],
		SprayIntervalTime:      d.RegisterData[2],
		FanControl:             d.RegisterData[3],
		LightControl:           d.RegisterData[4],
		ControllerMode:         d.RegisterData[5],
		SolenoidValveMode:      d.RegisterData[6],
		AddLightTimePeriod:     d.RegisterData[7],
		DeleteLightTimePeriod2: d.RegisterData[8],
		Manual:                 d.RegisterData[9],
		SecondCurrentThreshold: d.RegisterData[10],
		ParameterId:            d.RegisterData[11],
		ParameterValue:         d.RegisterData[12],
	}

	deviceControlEvent := DeviceControlEvent{
		Method: PayloadTypeMap[25],
		Params: deviceControlParams,
	}
	logrus.Info("deviceControlEvent:", deviceControlEvent)
	//deviceControlEvent转json
	payload, err := json.Marshal(deviceControlEvent)
	if err != nil {
		return err
	}
	// 发送数据到平台
	err = PublishEvent(d.Mac, payload)
	if err != nil {
		return err
	}

	return nil
}
